package com.itheima.service.impl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.exception.NotNullException;
import com.itheima.mapper.ClazzMapper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.ClazzQueryParam;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ClazzServiceImpl implements ClazzService {

    @Autowired
    private ClazzMapper clazzMapper;

    @Autowired
    private StudentMapper studentMapper;


    /***
     * 查询所有班级
     * @return
     */
    @Override
    public List<Clazz> list() {
        return clazzMapper.list(null);
    }


    /***
     * 删除
     * @param ids
     */
    @Override
    public void delete(List<Integer> ids) {
        //查询班级下是否有学生
        int count = studentMapper.countClazzStudents(ids);
        if(count>0){
            throw new NotNullException("对不起，当前班级下有学生，不能直接删除！");
        }

        clazzMapper.deleteBatch(ids);
    }


    /***
     * 修改操作
     * @param clazz
     */
    @Override
    public void update(Clazz clazz) {
        clazzMapper.updateById(clazz);
    }


    /***
     * 根据ID查询班级详情
     * @param id
     * @return
     */
    @Override
    public Clazz getClazzInfo(Integer id) {
        return clazzMapper.findById(id);
    }



    /***
     * 新增班级信息
     * @param clazz
     */
    @Override
    public void add(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        clazzMapper.insert(clazz);
    }

    @Override
    public PageResult page(ClazzQueryParam clazzQueryParam) {
        //分页操作
        PageHelper.startPage(clazzQueryParam.getPage(),clazzQueryParam.getPageSize());

        //集合数据查询
        List<Clazz> list = clazzMapper.list(clazzQueryParam);
        Page<Clazz> page = (Page<Clazz>) list;
        return new PageResult(page.getTotal(),list);
    }

}
